package net.lab1024.sa.base.module.support.rule.controller;

import com.alibaba.fastjson.JSONObject;
import org.mvel2.CompileException;
import org.mvel2.MVEL;
import org.mvel2.ParserContext;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class MvelValidator {
    
    // 定义合法的操作符
    private static final String[] VALID_OPERATORS = {"==", "!=", ">", ">=", "<", "<=", "contains", "matches", "in", "not in"};
    
    // 定义合法的逻辑运算符
    private static final String[] VALID_LOGICAL_OPERATORS = {"and", "or", "&&", "||"};
    
    /**
     * 验证 MVEL 表达式语法是否正确
     * @param expression MVEL 表达式
     * @return 验证结果，true 表示表达式语法正确
     */
    public static boolean validateSyntax(String expression) {
        try {
            ValidationResult result = validateWithDetails(expression);
            return result.isValid();
        } catch (Exception e) {
            System.err.println("验证过程中发生错误: " + e.getMessage());
            return false;
        }
    }

    public static ValidationResult validateWithDetailsNew(String expression) {ValidationResult result = new ValidationResult();

            JSONObject jsonObject = JSONObject.parseObject(expression);
        String os = jsonObject.getString("epl");
        try {
            ParserContext context = new ParserContext();
            MVEL.compileExpression(os, context);

            result.setValid(true);
            result.setMessage("表达式语法正确");
        } catch (CompileException e) {
            result.setValid(false);
            result.setMessage("表达式语法错误: " + e.getMessage());
//            result.setErrorPosition(e.getLineNumber(), e.getColumnNumber());
        } catch (Exception e) {
            result.setValid(false);
            result.setMessage("验证过程中发生错误: " + e.getMessage());
        }

        return result;
    }

    /**
     * 验证 MVEL 表达式并获取详细错误信息
     * @param expression MVEL 表达式
     * @return 验证结果对象，包含是否成功和错误信息
     */
    public static ValidationResult validateWithDetails(String expression) {
        ValidationResult result = new ValidationResult();
        
        if (expression == null || expression.trim().isEmpty()) {
            result.setValid(false);
            result.setMessage("表达式不能为空");
            return result;
        }

        try {
            // 1. 检查基本语法结构
            if (!validateBasicSyntax(expression)) {
                result.setValid(false);
                result.setMessage("表达式格式不正确，请检查操作符和字段名称");
                return result;
            }

            // 2. 检查操作符使用是否正确
            if (!validateOperators(expression)) {
                result.setValid(false);
                result.setMessage("表达式中包含不支持的操作符");
                return result;
            }

            // 3. 检查逻辑运算符使用是否正确
            if (!validateLogicalOperators(expression)) {
                result.setValid(false);
                result.setMessage("表达式中的逻辑运算符使用不正确");
                return result;
            }

            // 4. 尝试编译表达式
            MVEL.compileExpression(expression);
            
            result.setValid(true);
            result.setMessage("验证通过: 表达式语法正确");
        } catch (Exception e) {
            result.setValid(false);
            result.setMessage("验证失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 验证基本语法结构
     */
    private static boolean validateBasicSyntax(String expression) {
        // 移除多余的空格
        expression = expression.trim().replaceAll("\\s+", " ");
        
        // 检查是否包含基本的字段和值结构
        Pattern pattern = Pattern.compile("([a-zA-Z_][a-zA-Z0-9_]*\\s*[=!<>]+\\s*[^\\s]+)");
        Matcher matcher = pattern.matcher(expression);
        
        return matcher.find();
    }

    /**
     * 验证操作符使用是否正确
     */
    private static boolean validateOperators(String expression) {
        // 检查是否只使用了允许的操作符
        for (String operator : VALID_OPERATORS) {
            expression = expression.replace(operator, "");
        }
        
        // 检查是否还存在其他操作符
        Pattern pattern = Pattern.compile("[=!<>]+");
        Matcher matcher = pattern.matcher(expression);
        
        return !matcher.find();
    }

    /**
     * 验证逻辑运算符使用是否正确
     */
    private static boolean validateLogicalOperators(String expression) {
        // 移除所有合法的逻辑运算符
        for (String operator : VALID_LOGICAL_OPERATORS) {
            expression = expression.replaceAll("\\b" + operator + "\\b", "");
        }
        
        // 检查是否还存在其他逻辑运算符
        Pattern pattern = Pattern.compile("\\b(and|or|&&|\\|\\|)\\b");
        Matcher matcher = pattern.matcher(expression);
        
        return !matcher.find();
    }

    /**
     * 验证结果类
     */
    public static class ValidationResult {
        private boolean valid;
        private String message;
        private int line = -1;
        private int column = -1;

        public boolean isValid() {
            return valid;
        }

        public void setValid(boolean valid) {
            this.valid = valid;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public void setErrorPosition(int line, int column) {
            this.line = line;
            this.column = column;
        }

        @Override
        public String toString() {
            return message;
        }
    }
}